<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\adminapi\controller\v1\platform\wxapp;

use app\adminapi\controller\v1\platform\PlatformController;
use app\common\model\addon\Addons;
use app\common\model\platform\Platform;
use app\common\model\platform\PlatformAddon;
use app\common\model\platform\PlatformWxapp;
use hiduoke\services\FormBuilder as Form;
use think\App;
use think\Request;

class Wxapp extends PlatformController
{
    /**
     * @var PlatformWxapp
     */
    public $model;
    /**
     * @var Platform
     */
    public $PlatformModel;

    public function __construct(App $app, PlatformWxapp $model)
    {
        parent::__construct($app);
        $this->model = $model;
    }

    /**
     * 显示微信平台列表
     * @Route("wxapp", method="GET")
     * @return \think\Response
     */
    public function index()
    {
        return $this->success("ok");
    }

    /**
     * 显示创建微信平台表单页.
     * @Route("wxapp/create", method="GET")
     * @return \think\Response
     */
    public function create()
    {
        $rule = array();
        //创建表单
        $form = Form::createForm("/platform/wxapp/index")->setMethod("POST");
        //新增表单
        $rule[] = Form::input('name', '小程序集合名称', "")->required();
        $rule[] = Form::dkImage('logo', '图标', "");
        $rule[] = Form::input('sort', '排序', "0");
        $rule[] = Form::input('description', '描述', "");
        $form->setTitle("新增小程序集合名称")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 保存新建的微信平台
     * @Route("wxapp", method="POST")
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $wallet = $this->userInfo['wallet'];
        if ($wallet['wxapp'] <= $wallet['use_count']['wxapp']) {
            return $this->error("创建次数不足");
        }
        $formData = $request->post('formData', []);
        $platform = new Platform();
        $platform_data = array(
            "type"        => 2,
            "uid"         => $this->userInfo['uid'],
            "name"        => $formData['name'],
            "description" => $formData['description'],
            "logo"        => $formData['logo'],
            "sort"        => $formData['sort'],
        );
        $platform->save($platform_data);
//        $wxapp_data = array(
//            "plaid"    => $platform->plaid,
//            "name"     => $formData['name'],
//            "original" => $formData['original'],
//            "appid"    => $formData['appid'],
//            "secret"   => $formData['secret'],
//        );
//        $this->model->save($wxapp_data);
        return $this->success("新增成功", ['plaid' => $platform->plaid]);
    }

    /**
     * 显示指定的微信平台
     * @Route("wxapp/id", method="GET")
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑微信平台表单页.
     * @Route("wxapp/id/edit", method="GET")
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $rule = array();
        //创建表单
        $platform = new Platform();
        $row = $platform->where(['plaid' => $id])->find();
        if (!$row) {
            return $this->error("当前平台不存在");
        }
        $form = Form::createForm("/platform/wxapp/index/" . $id)->setMethod("PUT");
        //新增表单
        $rule[] = Form::input('name', '小程序集合名称', $row->name)->required();
        $rule[] = Form::dkImage('logo', '图标', $row->logo);
        $rule[] = Form::input('sort', '排序', $row->sort);
        $rule[] = Form::input('description', '描述', $row->description);
        $options = $this->getAddonsOption($id,false);
        $rule[] = Form::select('addon_name', "默认小程序", $row->addon_name)->options($options)->required();
        $form->setTitle("编辑小程序集合")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 保存更新的微信平台
     * @Route("wxapp/id", method="PUT")
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $formData = $request->post('formData', []);
        $platform = new Platform();
        $platform_data = $platform->where(['plaid' => $id])->find();
        if (!$platform_data) {
            return $this->error("当前平台不存在");
        }
        $platform_data->save([
            "type"        => 2,
            "name"        => $formData['name'],
            "description" => $formData['description'],
            "logo"        => $formData['logo'],
            "sort"        => $formData['sort'],
            "addon_name"  => $formData['addon_name'],
        ]);
        return $this->success("编辑成功");
    }

    /**
     * 删除指定微信平台
     * @Route("wxapp/id", method="DELETE")
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }


    public function getWxappMessage()
    {
        $plaid = input('plaid', 0);
        if (!$plaid) {
            return $this->error('平台ID不存在');
        }
        $res = $this->model->getPlatformDetails($plaid);
        if (!$res) {
            return $this->error('平台不存在');
        }
        $data = array(
            'api_url'        => $res['api_url'],
            'token'          => $res['token'],
            'encodingaeskey' => $res['encodingaeskey']
        );
        return $this->success('ok', $data);
    }

    public function editWxappMessage()
    {
        $formData = $this->request->post('formData', []);
        $plaid = input('plaid', 0);
        $wxapp = new PlatformWxapp();

        $wxapp_data = $wxapp->where(['plaid' => $plaid])->find();
        if (!$wxapp_data) {
            return $this->error("当前公众平台不存在");
        }
        $wxapp_data->save([
            "token"          => $formData['token'],
            "encodingaeskey" => $formData['encodingaeskey'],
        ]);
        return $this->success("修改成功");
    }

    // 第一次进来，没有添加任何应用

    // 添加了应用，但是应用没有对应小程序配置

    // 收个添加小程序配置设置为默认

    // 配置内容以页面的addon_name为标准，而非数据库的default


    /**
     * 获取添加应用列表
     */
    public function getAddonsOption($plaid = 0, $isApi = true)
    {
        $options = [];
        $names = [];
        foreach ($this->model->where(['plaid' => $plaid])->select() as $key => $value) {
            $names[] = $value['addon_name'];
        }
        $addons = (new Addons())->whereIn('name', $names)->select();
        foreach ($addons as $key => $value) {
            $options[] = [
                'value' => $value['name'],
                'label' => $value['title']
            ];
        }
        if ($isApi) {
            return $this->success('', $options);
        } else {
            return $options;
        }
    }


    /**
     * 切换默认程序
     */
    public function changeDefaultAddon($plaid, $addon_name)
    {
        (new Platform())->where(['plaid' => $plaid])->save(['addon_name' => $addon_name]);
        return $this->success('修改成功');
    }


    /**
     * 获取当前默认应用
     */
    public function getDefaultAddon($plaid = 0)
    {
        $addon_name = (new Platform())->where(['plaid' => $plaid])->value('addon_name');
        $addon = (new Addons())->where(['name' => $addon_name])->find();
        return $this->success('', $addon);
    }

    /**
     * 获取小程序表单
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function getWxappForm($plaid = 0)
    {
        $addon_name = (new Platform())->where(['plaid' => $plaid])->value('addon_name');
        if (!$addon_name) {
            return $this->error('没有添加应用');
        }
        $row = $this->model->where(['plaid' => $plaid, 'addon_name' => $addon_name])->findOrEmpty();
        $rule = array();
        //创建表单
        $form = Form::createForm("/platform/wxapp/index/saveWxapp")->setMethod("POST");
        //新增表单
        $rule[] = Form::hidden('id', $row->id);
        $rule[] = Form::input('name', '小程序名称', $row->name ?? '')->required();
        $rule[] = Form::input('appid', 'AppId', $row->appid ?? '')->required();
        $rule[] = Form::input('secret', 'AppSecret', $row->secret ?? '')->required();
        $rule[] = Form::input('original', '原始id', $row->original ?? '');
        $rule[] = Form::dkImage('logo', '图标', $row->logo ?? '');
        $form->setTitle("设置小程序")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function saveWxapp()
    {
        $formData = $this->request->post('formData', []);
        $wxapp_data = $this->model->where(['id' => $formData['id']])->find();
        if (!$wxapp_data) {
            return $this->error("当前小程序应用不存在");
        }
        $wxapp_data->save([
            "name"     => $formData['name'],
            "original" => $formData['original'],
            "appid"    => $formData['appid'],
            "secret"   => $formData['secret'],
            "logo"     => $formData['logo'],
        ]);
        return $this->success("编辑成功");
    }

}
